package api

import (
	"context"
	"errors"
	"github.com/robfig/cron/v3"
	"go-chain-api/global"
	models "go-chain-api/internal/model"
	"go-chain-api/utils/mail"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"log"
	"time"
)

func SendEmail() {
	// 创建一个 cron 定时器
	c := cron.New()
	_, err := c.AddFunc("0 0 * * * ", job)
	if err != nil {
		log.Fatal(err)
	}
	// 开始执行定时任务
	c.Start()
	// 阻塞主goroutine，防止程序退出
	select {}
}

func job() {
	log.Println("定时任务执行：", time.Now())
	var userList []models.User
	var emailList []string
	var maturityList []string
	userClient := global.DBEngine.Database(global.DbConfig.DbName).Collection("user")
	filter := bson.D{{"maturityTime", bson.D{{"$ne", 0}}}}
	cursor, err := userClient.Find(context.TODO(), filter)
	if err != nil && !errors.Is(err, mongo.ErrNoDocuments) {
		log.Println("定时任务执行错误用户：", err)
		return
	}
	err = cursor.All(context.TODO(), &userList)
	if err != nil {
		log.Println("定时任务执行错误解析：", err)
		return
	}
	for _, user := range userList {
		if user.MaturityTime <= time.Now().Unix()+259200 {
			emailList = append(emailList, user.Email)
		}
		if user.MaturityTime <= time.Now().Unix() {
			maturityList = append(maturityList, user.Email)
		}

	}
	if len(emailList) > 0 {

		for _, s := range emailList {
			str := "尊敬的会员：\n\n您好！\n\n您的BlockWatch会员资格即将到期，为避免影响您继续享受我们的优质服务，请您尽快进行续费。续费后，您将继续享有会员专属权益和福利。\n\n您可以通过我们的官方网站 https://blockwatch.skysp.info/login 进行续费，或联系客服协助完成。请尽快操作，以免影响您的体验。\n\n如有任何疑问，请随时联系我们。感谢您一直以来的支持，期待您继续成为我们的尊贵会员！\n\n祝您生活愉快！"
			// 发送普通单发邮件
			emailParams := mail.Options{
				MailHost: global.EmailConfig.Host,
				MailPort: global.EmailConfig.Port,
				MailUser: global.EmailConfig.User,
				MailPass: global.EmailConfig.Password,
				MailTo:   s,
				Subject:  "您的会员即将过期",
				Body:     str,
			}
			mail.Send(&emailParams)
			//_, err := mail.SendSingleEmail(0, s, global.EmailConfig.FromEmail, true, global.EmailConfig.FromEmail, "中国芯", str, "您的会员即将过期", "")
			if err != nil {
				log.Println("发送有邮件失败:", s)
				continue
			}
		}
		if err != nil {
			log.Println("定时任务发送邮件错误：", err)
		}
	}
	if len(maturityList) > 0 {
		filter := bson.D{{"email", bson.D{{"$in", maturityList}}}}
		update := bson.D{
			{"$set", bson.D{
				{"maturityTime", 0},
			}},
		}
		_, err := userClient.UpdateMany(context.TODO(), filter, update)
		if err != nil {
			log.Println("会员更新失败!")
		}
	}

}
